package com.example.shushiyunsst.fragment.main.home.child.icon_sst

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.arch.core.executor.ArchTaskExecutor
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseDataBindingFragment
import com.example.library_common.glidmodule.GlideApp
import com.example.library_common.global.AppGlobals
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.ICON_TRANSFER_NOTIFY
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_LIST
import com.example.library_common.utils.timer.BaseTimerTask
import com.example.library_common.utils.timer.ITimerListener
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.ForLendingFragmentBinding
import com.example.shushiyunsst.fragment.getUserBalanceInfo
import com.example.shushiyunsst.fragment.main.constant.CURRENT_DEVICE_TOKEN
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.*
import com.example.shushiyunsst.util.*
import com.example.shushiyunsst.util.push.helper.PushHelper
import com.example.wallet.db.UserInfoManager
import com.example.wallet.utils.Preference
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.core.ImageViewerPopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.lxj.xpopup.interfaces.XPopupImageLoader
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.util.*

/**
 * 待放款
 * */
class ForLendingFragment : BaseDataBindingFragment<ForLendingFragmentBinding>(),
    View.OnClickListener {

    companion object {
        fun newInstance(toId: String): ForLendingFragment {
            val args = Bundle()
            args.putString("toId", toId)
            val fragment = ForLendingFragment()
            fragment.arguments = args
            return fragment
        }
    }

//    private var mBean: SaveTxSellOrderBean? = null

    private var toId: String? = null

    private var mResultBean: MyOrderResultBean? = null

    private lateinit var mToolbar: Toolbar

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        toId = arguments?.getString("toId")
    }


    override fun layoutId(): Int {
        return R.layout.for_lending_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mToolbar = view.findViewById(R.id.mToolbar)
//        mToolbar.setTitle(R.string.for_lending)
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        viewBinder.onViewClick = this

        queryTxOrderById()


//        showPay()
    }

    private fun queryTxOrderById() {

        viewBinder.mProgressBar.visibility = View.VISIBLE

        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val map = mapOf(
            "toid" to toId,
            "uid" to userInfo?.uid
        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.queryTxOrderById)
            .success {

                parseQueryTxOrder(it)
                viewBinder.mProgressBar.visibility = View.GONE
                //                viewBinder.mProgressBar.visibility=View.GONE

            }.failure {
                Toast.makeText(_mActivity, "获取订单详情失败", Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
            }.build().post()
    }

    private fun parseQueryTxOrder(it: String?) {
        mResultBean = JSON.parseObject(it, MyOrderResultBean::class.java)
        viewBinder.bean = mResultBean
        mToolbar.title = mResultBean?.order?.orderDesc
        when (mResultBean?.order?.orderStatus) {
            ON_PAYING -> {
                viewBinder.fanBi.isSelected=true

                viewBinder.cancelTv.visibility = View.GONE
                viewBinder.fanBi.text = "等待对方付款中"


            }
            PAYED_WAITING -> {
                viewBinder.fanBi.text = "去放币"

                viewBinder.fanBi.isSelected=false

                viewBinder.cancelTv.visibility = View.VISIBLE
            }
        }

        mResultBean?.order?.getPayTypeUI(mResultBean?.payment)
        showPay()
    }

    private fun showPay() {
        when (mResultBean?.order?.payType) {
            A_LI_PAY -> {
                viewBinder.aliPayLayout.visibility = View.VISIBLE
                viewBinder.weiChatPayLayout.visibility = View.GONE
                viewBinder.bankCardPayLayout.visibility = View.GONE
            }
            WEI_CHAT_PAY -> {
                viewBinder.aliPayLayout.visibility = View.GONE
                viewBinder.weiChatPayLayout.visibility = View.VISIBLE
                viewBinder.bankCardPayLayout.visibility = View.GONE
            }
            BANK_PAY -> {
                viewBinder.aliPayLayout.visibility = View.GONE
                viewBinder.weiChatPayLayout.visibility = View.GONE
                viewBinder.bankCardPayLayout.visibility = View.VISIBLE
            }
        }
//        mBean?.order?.payType = payType
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.cancelTv -> {
                ARouter.getInstance()
                    .build(COMPLAINT)
                    .withString(TO_ID, mResultBean?.order?.toid.toString())
                    .startNavigation(this)
            }
            R.id.aliPayPaying_way -> {
                when {

                    mResultBean?.payment?.isSupportWx == 1 -> {
                        mResultBean?.order?.payType = WEI_CHAT_PAY
                    }
                    mResultBean?.payment?.isSupportBank == 1 -> {
                        mResultBean?.order?.payType = BANK_PAY

                    }
                }
                showPay()

            }
            R.id.weiChatPayPaying_way -> {
//                payType = BANK_PAY
                when {
                    mResultBean?.payment?.isSupportAipay == 1 -> {
                        mResultBean?.order?.payType = A_LI_PAY
                    }

                    mResultBean?.payment?.isSupportBank == 1 -> {
                        mResultBean?.order?.payType = BANK_PAY
                    }
                }
                showPay()
            }
            R.id.bankCardPayPaying_way -> {
                when {
                    mResultBean?.payment?.isSupportAipay == 1 -> {
                        mResultBean?.order?.payType = A_LI_PAY
                    }
                    mResultBean?.payment?.isSupportWx == 1 -> {
                        mResultBean?.order?.payType = WEI_CHAT_PAY
                    }

                }
                showPay()
//                payType = A_LI_PAY

            }
            R.id.bankCardPayBankNo -> {
                clipboard("bankCardPayBankNo", mResultBean?.payment?.bankNo ?: "")
            }

            R.id.bankCardPayRealName -> {
                clipboard("bankCardPayRealName", mResultBean?.payment?.realName ?: "")
            }

            R.id.bankCardPayBankNameChild -> {
                clipboard("bankCardPayBankNameChild", mResultBean?.payment?.bankNameChild ?: "")
            }

            R.id.bankCardPayBankName -> {
                clipboard("bankCardPayBankNameChild", mResultBean?.payment?.bankName ?: "")
            }

            R.id.weiChatPayAccount -> {
                clipboard("weiChatPayAccount", mResultBean?.payment?.wxAccount ?: "")
            }

            R.id.weiChatPayRealName -> {
                clipboard("weiChatPayRealName", mResultBean?.payment?.realName ?: "")
            }

            R.id.aliPayAccount -> {
                clipboard("aliPayAccount", mResultBean?.payment?.alipayAccount ?: "")
            }

            R.id.aliPayRealName -> {
                clipboard("aliPayAccount", mResultBean?.payment?.realName ?: "")
            }

            R.id.aliPayPic -> {
                val imageViewerPopupView = ImageViewerPopupView(_mActivity)
                imageViewerPopupView.setImageUrls(listOf(mResultBean?.payment?.alipayUrl))
                imageViewerPopupView.setXPopupImageLoader(object : XPopupImageLoader {
                    override fun loadImage(position: Int, uri: Any, imageView: ImageView) {
                        GlideApp.with(this@ForLendingFragment)
                            .load(uri)
                            .centerInside()
                            .into(imageView)
                    }

                    override fun getImageFile(context: Context, uri: Any): File {
                        return File(uri.toString())
                    }
                })
                XPopup.Builder(_mActivity)
                    .asCustom(imageViewerPopupView)
                    .show()
            }

            R.id.weiChatPayPic -> {
                val imageViewerPopupView = ImageViewerPopupView(_mActivity)
                imageViewerPopupView.setImageUrls(listOf(mResultBean?.payment?.wxUrl))
                imageViewerPopupView.setXPopupImageLoader(object : XPopupImageLoader {
                    override fun loadImage(position: Int, uri: Any, imageView: ImageView) {
                        GlideApp.with(this@ForLendingFragment)
                            .load(uri)
                            .centerInside()
                            .into(imageView)
                    }

                    override fun getImageFile(context: Context, uri: Any): File {
                        return File(uri.toString())
                    }
                })
                XPopup.Builder(_mActivity)
                    .asCustom(imageViewerPopupView)
                    .show()
            }

            R.id.fanBi -> {
                when(mResultBean?.order?.orderStatus){
                    PAYED_WAITING->{
                        handFanBiPop()
                    }
                    ON_PAYING->{
                        Toast.makeText(_mActivity,"等待对方付款，请等待",Toast.LENGTH_LONG).show()
                    }
                }

            }
        }
    }

    private fun handFanBiPop() {
        val mPop = PayingPassWordVerifyPop(_mActivity)
        XPopup.Builder(_mActivity)
            .setPopupCallback(object : SimpleCallback() {
                override fun onDismiss(popupView: BasePopupView?) {
                    super.onDismiss(popupView)
                    if (mPop.getIsOnVerifyPop()) {
                        if (mPop.getVerifyPop()) {
                            handFanBi()
                        } else {
                            Toast.makeText(_mActivity, "支付密码错误", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            })
            .asCustom(mPop)
            .show()
    }

    override fun handMessage(msg: MessageWrap?) {
//        super.handMessage(msg)
        if (msg?.message == ICON_TRANSFER_NOTIFY) {
            queryTxOrderById()
        }
    }

    private fun handFanBi() {
        val userInfo =
            UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

        val map = mapOf(
            "toid" to mResultBean?.order?.toid,
            "uid" to userInfo?.uid
        )


        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.updateTxOrder)
            .success {
                getUserBalanceInfo(AppGlobals.getApplication())
                parseUpdateTxOrder(it)

            }.failure {
                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_SHORT).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }.build().post()
    }

    private fun parseUpdateTxOrder(it: String) {
        val obj = JSON.parseObject(it, UpdateTxOrderBean::class.java)
        fanBiPushMsg(obj)
        Toast.makeText(_mActivity, "发送成功", Toast.LENGTH_SHORT).show()
        EventBus.getDefault().post(MessageWrap.getInstance(TO_REFRESH_LIST))
        onBackPressedSupport()
    }


    @SuppressLint("RestrictedApi")
    private fun fanBiPushMsg(obj: UpdateTxOrderBean) {
        ArchTaskExecutor.getIOThreadExecutor().execute {
            try {
                obj.pushMsg.type = FAN_BI
                obj.pushMsg.orderId = obj.order.txNo
                val deviceTokens = obj.pushMsg.deviceToken
                val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
                val pushHelper = PushHelper()
                val broadcast = PushHelper.getAndroidBroadcast()
                broadcast.setTitle("SST放币")
                broadcast.setDeviceToken(deviceTokens)
                broadcast.setPlaySound(true)
                broadcast.setTicker("SST放币")
                broadcast.setTitle("${userInfo?.nickName} 向你放出 ${obj.order?.totalPrice} 个 SSL")
                broadcast.setText("${userInfo?.nickName} 向你放出 ${obj.order?.totalPrice} 个 SSL")
                broadcast.setCustomField(JSON.toJSONString(obj.pushMsg))
                pushHelper.sendAndroidBroadcast(broadcast)
            } catch (e: Exception) {
                e.printStackTrace()
            }


        }
    }


    override fun onPause() {
        super.onPause()
        hideSoftInput()
    }


}